package top.anydata.lifeofcode.lifesystem.service.common.impl;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import top.anydata.lifeofcode.lifesystem.service.common.ICommonService;
import top.anydata.lifeofcode.lifesystem.util.CommonUtils;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 功能描述:公共基础服务
 *
 * @author <a href="mailto:caingao@anydata.top">CainGao</a>
 * @version V_1.0
 * @date 2024/2/6 3:40 PM
 */
@Service
public class CommonServiceImpl implements ICommonService {

    private final static String CAPTCHA_PREFIX = "sys:common:captcha:";

    private final StringRedisTemplate redisTemplate;

    public CommonServiceImpl(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public Map<String, String> generateCaptcha() {
        String captchaId = UUID.randomUUID().toString();
        String captchaText = CommonUtils.generateCaptcha(4);
        String captchaImg = CommonUtils.generateCatchaImg(captchaText);
        redisTemplate.opsForValue().set(
                CAPTCHA_PREFIX+captchaId,
                captchaText,
                5,
                TimeUnit.MINUTES
        ); // 验证码5分钟后过期
        return Map.of("captchaId", captchaId, "captcha", captchaImg);
    }

    @Override
    public boolean validateCaptcha(String captchaId, String captcha) {
        String storedCaptcha = redisTemplate.opsForValue().get(CAPTCHA_PREFIX+captchaId);
        if (storedCaptcha != null && storedCaptcha.equalsIgnoreCase(captcha)) {
            redisTemplate.delete(CAPTCHA_PREFIX+captchaId); // 验证成功后删除验证码
            return true;
        }
        return false;
    }
}
